import pandas as pd
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity

class RecommendationService:
    def __init__(self, csv_path):
        """
        初始化推荐服务类
        参数:
        - csv_path: 包含用户与商品交互的 CSV 文件路径
        """
        self.csv_path = csv_path
        self.user_item_matrix = None
        self.user_to_index = None
        self.goods_to_index = None
        self.index_to_user = None
        self.index_to_goods = None

    def load_data(self):
        """
        加载 CSV 数据并构建用户-商品矩阵
        """
        df = pd.read_csv(self.csv_path)
        unique_users = df['user_id'].unique()
        unique_goods = df['goods_id'].unique()

        print(unique_goods)
        print(unique_users)

        # 创建映射
        self.user_to_index = {int(user): idx for idx, user in enumerate(unique_users)}
        print(self.user_to_index,6666666666666666666666)
        self.goods_to_index = {int(goods): idx for idx, goods in enumerate(unique_goods)}
        print(self.goods_to_index)
        self.index_to_user = {idx: user for user, idx in self.user_to_index.items()}
        print(self.index_to_user)
        self.index_to_goods = {idx: goods for goods, idx in self.goods_to_index.items()}
        print(self.index_to_goods)
        # 初始化用户-商品矩阵
        self.user_item_matrix = np.zeros((len(unique_users), len(unique_goods)))

        # 填充矩阵
        for _, row in df.iterrows():
            user_idx = self.user_to_index[row['user_id']]
            goods_idx = self.goods_to_index[row['goods_id']]
            self.user_item_matrix[user_idx, goods_idx] = 1

    def recommend_items(self, user_id, top_n=20):
        """
        基于余弦相似度为目标用户推荐商品
        参数:
        - user_id: 目标用户的 ID
        - top_n: 推荐商品的数量
        返回:
        - recommended_goods: 推荐的商品 ID 列表
        """
        if self.user_item_matrix is None:
            raise ValueError("User-Item matrix is not initialized. Call `load_data` first.")
        print(user_id,999999999999999999999999999999)
        # 确保用户存在于映射中
        if int(user_id) not in self.user_to_index:
            print('not found',user_id)

            return []

        # 获取目标用户索引
        target_user_index = self.user_to_index[user_id]
        print(target_user_index,6666666666666666666666)

        # 计算用户相似度
        similarity_matrix = cosine_similarity(self.user_item_matrix)
        target_user_similarity = similarity_matrix[target_user_index]
        target_user_similarity[target_user_index] = 0  # 自身相似度设为 0

        # 获取最相似的用户
        similar_users = np.argsort(target_user_similarity)[::-1]

        # 获取目标用户的交互记录
        target_user_interactions = self.user_item_matrix[target_user_index]

        # 创建推荐列表
        recommended_items = []
        print('1111111111111111111111111111111111111111111111111')
        for similar_user in similar_users:
            similar_user_interactions = self.user_item_matrix[similar_user]
            items_to_recommend = np.where((similar_user_interactions == 1) & (target_user_interactions == 0))[0]

            for item in items_to_recommend:
                if item not in recommended_items:
                    recommended_items.append(item)
                    if len(recommended_items) >= top_n:
                        break
            if len(recommended_items) >= top_n:
                break

        # 将索引映射回商品 ID
        recommended_goods = [self.index_to_goods[item] for item in recommended_items]
        print(recommended_goods,999999999999999999999999999999999)
        return recommended_goods